package com.xiaoyu.lanling.feature.verify.activity

import `in`.srain.cube.util.CLog
import `in`.srain.cube.util.log.LogEvent
import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import androidx.annotation.Keep
import com.alibaba.security.realidentity.RPEventListener
import com.alibaba.security.realidentity.RPResult
import com.alibaba.security.realidentity.RPVerify
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.user.UserExtraUpdateEvent
import com.xiaoyu.lanling.event.verify.GetVerifyTokenEvent
import com.xiaoyu.lanling.event.verify.VerifyResultEvent
import com.xiaoyu.lanling.feature.user.model.UserExtra.VerifyStatus.FAILED
import com.xiaoyu.lanling.feature.user.model.UserExtra.VerifyStatus.SUCCESS
import com.xiaoyu.lanling.feature.user.model.UserExtra.VerifyStatus.UNVERIFIED
import com.xiaoyu.lanling.feature.user.model.UserExtra.VerifyStatus.VERIFYING
import com.xiaoyu.lanling.feature.verify.data.VerifyData
import com.xiaoyu.lanling.log.AppLogClient
import com.xiaoyu.lanling.media.image.ImageViewUtil
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_verify_human.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Keep
class VerifyHumanActivity : AppCompatToolbarActivity() {

    private var mDisposable: Disposable? = null

    private val requestTag = Any()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_verify_human)
        initToolbar()
        setTitle(R.string.fate_preference_verify_title)

        initBind()
        initEvent()
        initData()
    }

    private fun initData() {
        ImageViewUtil.loadAvatarRound(avatar, UserData.getInstance().user, 120)
        getVerifyResult()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable?.dispose()
    }

    private fun initBind() {
        button.setOnClickDebounceListener {
            button.isEnabled = false
            VerifyData.getFaceVerifyToken(requestTag)
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: GetVerifyTokenEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }

                verify(event.verifyToken)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: VerifyResultEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                showData(event.result)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: UserExtraUpdateEvent) {
                getVerifyResult()
            }
        })
    }

    private fun showData(result: String) {
        when (result) {
            UNVERIFIED -> {
                status_image.setImageResource(R.drawable.icon_verify_human_unverified)
                button.setText(R.string.verify_human_unverified)
                button.isEnabled = true
            }
            VERIFYING -> {
                status_image.setImageResource(0)
                button.setText(R.string.verify_human_verifying)
                button.isEnabled = false
            }
            SUCCESS -> {
                status_image.setImageResource(R.drawable.icon_verify_human_sucess)
                button.setText(R.string.verify_human_sucess)
                button.isEnabled = false
            }
            FAILED -> {
                status_image.setImageResource(R.drawable.icon_verify_human_fail)
                button.setText(R.string.verify_human_fail)
                button.isEnabled = true
            }
        }
    }

    private fun verify(verifyToken: String) {
        mDisposable = RxPermissions(this)
                .request(Manifest.permission.CAMERA)
                .filter { !TextUtils.isEmpty(verifyToken) }
                .subscribe { granted ->
                    if (granted) {
                        onVerify(verifyToken)
                    } else {
                        GlobalUI.getInstance().showToast("请授予相机权限后再试")
                    }
                }
    }

    private fun onVerify(verifyToken: String) {
        RPVerify.start(this, verifyToken, object : RPEventListener() {
            override fun onFinish(result: RPResult, code: String, message: String) {
                val logEvent  = LogEvent("verifyFace")
                logEvent.putData("code", result.code)
                logEvent.putData("message", result.message)
                AppLogClient.instance.addLog(logEvent)

                if (result == RPResult.AUDIT_NOT) {
                    GlobalUI.getInstance().showToastForLong(message)
                }
                getVerifyResult()
            }
        })
    }

    private fun getVerifyResult() {
        VerifyData.verifyResult(requestTag)
    }
}